import { Button, Statistic,AutoComplete, message, Row, Col, Card, Input, Form } from 'antd';
import React, {
  useState,
  useRef,
  useEffect
} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type {
  ProColumns,
  ActionType
} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProCard from '@ant-design/pro-card';
import { queryRule,selectActivity, selectStudent,queryInfo,taskExport,selectClass,selectTeacher,selectTask,initFileUploadTask} from './service';
import { downloadFile } from '@/utils/utils';
import moment from 'moment';
import { baseUrl } from '@/utils/httpUrl';
const { Option } = AutoComplete;
const TableList: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const { activityId } = props.location.query

  const [options, setOptions] = useState([]);
  const [uid, setUid] = useState<any>()

  const [classOptions,setClassOptions] = useState([])
  const [classId,setClassId] = useState()

  const [teacherOptions,setTeacherOptions] = useState([])
  const [teacherId,setTeacherId] = useState()

  const [taskOptions,setTaskOptions] = useState([])
  const [taskId,setTaskId] = useState()

  const [firstRender, setFirstRender] = useState(true)
  const statusMap = {
    '0': '未开始',
    '1': '已开始',
    '2': '已完成'
  }
  const taskExportHandler = async function () {
    if(!uid){
      var url = await taskExport({activityId:String(activityId)})
    } else{
      var url = await taskExport({activityId:String(activityId),uid:String(uid)})
    }
    downloadFile(`整体做题统计-${moment(new Date().getTime()).format('YYYY-MM-DD HH-mm-ss')}`,url,'.xls')
  }
  const fetchData = async () => {
    const data = await queryRule({ activityId, pageSize: 20, pageNo: 1 })
    const info = await queryInfo({ activityId })
    if(data.code === 500){
      message.error(data.message)
      return
    }
    setBaseInfo(data.result.activity)
    modifyMsgData(data.result)
    onTaskSearch()
  }
  const onSelect = (data: any, option: any) => {
    setUid(option.key)
  };
  const onSearch = async (key: string) => {
    const data = await selectStudent( {
      phone:key,
      activityId
    })
    function getStudentSearchOptions(keys: any, data: any) {
      return  !keys ? [] : data.result.map((item: { uid: any; nickname: any; phone: any}) => ({
        id: item.uid,
        label: (item.nickname||'') + `  (${item.phone})`,
        value: item.nickname + `  (${item.phone})`
      }))
    }
    const options =  getStudentSearchOptions(key,data)
    setOptions(options);
  };

  const onClassSelect = (data: any, option: any) => {
    setClassId(option.key)
  };
  const onClassSearch = async (key: string) => {
    const data = await selectClass( {
      name:key,
      activityId
    })
    function getSearchOptions(keys: any, data: any) {
      return  !keys ? [] : data.result.map((item: { id: any; name: any;}) => ({
        id: item.id,
        label: (item.name||'') + `  (${item.id})`,
        value: item.name + `  (${item.id})`
      }))
    }
    const options =  getSearchOptions(key,data)
    setClassOptions(options);
  };

  const onTeacherSelect = (data: any, option: any) => {
    setTeacherId(option.key)
  };
  const onTeacherSearch = async (key: string) => {
    const data = await selectTeacher( {
      param:key,
      activityId
    })
    function getSearchOptions(keys: any, data: any) {
      return  !keys ? [] : data.result.map((item: { uid: any; realName: any; phone: any}) => ({
        id: item.uid,
        label: (item.realName||'') + `  (${item.phone})`,
        value: item.realName + `  (${item.phone})`
      }))
    }
    const options =  getSearchOptions(key,data)
    setTeacherOptions(options);
  };

  const onTaskSelect = (data: any, option: any) => {
    setTaskId(option.key)
  };
  const onTaskSearch = async () => {
    const data = await selectTask({
      activityId
    })
    function getSearchOptions(keys: any, data: any) {
      return  !keys ? [] : data.result.map((item: { mapId: any; mapName: any;}) => ({
        id: item.mapId,
        label: item.mapName ,
        value: item.mapName
      }))
    }
    const options =  getSearchOptions(key,data)
    setTaskOptions(options);
  };

  const createColumns = (data,gamePaperData) => {
    const columnsMap = new Map()
    data.map(item => {
        columnsMap.set(item.collId,item.label)
    })
    const column = []
      for (const k in gamePaperData.passPaperResultList) {
       column.push({
         title: columnsMap.get(Number(gamePaperData.passPaperResultList[k].collId)),
         dataIndex: gamePaperData.passPaperResultList[k].collId,
         hideInSearch: true,
         render:(val)=>(
            val.label ==='无' ?
            <>无</> : val.passPaperId ? <a target="_blank" href={`${baseUrl.webview}/?scene=quizViewDetail&paperId=${val.passPaperId}`} rel="noreferrer">{val.label}</a>  : <>-</>
         )
      })
    }
    console.log(baseColumns.concat(column))
    setColumns(baseColumns.concat(column))
  }

  const modifyMsgData = (data) => {
   const taskMap = data.passPaperCollModelList
   const json = data.activityPassUserDataRespPage.records.map(item=>{
     const _json = {}
     for(const k in item.passPaperResultList){
      _json[item.passPaperResultList[k].collId] = {
        label:item.passPaperResultList[k].result,
        passPaperId:item.passPaperResultList[k].passPaperId
      }
     }
     return Object.assign(item,_json)
   })
    createColumns(taskMap, json[0])
    setFirstRender(false)
    console.log(json)
    return json
  }

  useEffect(() => {
    if (activityId) {
      fetchData()
    }
  }, [activityId])
  const [columns, setColumns] = useState(baseColumns)
  const [baseInfo, setBaseInfo] = useState<any>()
  const baseColumns: ProColumns<{}>[] = [

    {
      title: '用户id',
      dataIndex: 'uid',
      hideInSearch: true
    },

    {
      title: '用户昵称',
      dataIndex: 'nickname',
      ellipsis:true,
      width: 150,
      hideInSearch: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      hideInSearch: true
    },
    {
      title: '班级',
      dataIndex: 'groupName',
      hideInSearch: true
    },
    {
      title: '辅导老师',
      dataIndex: 'teacherName',
      hideInSearch:true
    },
    {
      title:'关卡名称',
      dataIndex: 'mapName',
      hideInSearch: true
    }
  ];
  const [lock,setLock] = useState(false)
  const exportExcel = async () => {
    if (!activityId) {
      message.error('课程ID不能为空')
      return
    }
    setLock(true)
    setTimeout(()=>{
      setLock(false)
    },5000)
   const res = await initFileUploadTask({
    activityId,
    uid,
    groupId:classId,
    teaId:teacherId,
    mapId:taskId,
   })
   if(res.code === 200){
     message.success('已加入下载列表，5s后可再次导出数据')
   } else {
     message.error(res.message)
   }
  }
  const [form] = Form.useForm();
  const onFinish = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  }
  const onReset = () => {
    window.location.reload()
  };
  return (
    <PageContainer>
      <Card style={{marginBottom:'20px'}}>
        <Form form={form} onFinish={onFinish} style={{'paddingBottom':'0px'}}>
          <Row gutter={[16,16]} >

          <Col span={8}>
            <Form.Item label="手机号" name="key">
              <AutoComplete
                onSelect={onSelect}
                onSearch={onSearch}
                placeholder="请选择"
                onChange={(value) => {
                  if (!value) {
                    setUid()
                  }
                }}
              >
                {options.map((item) => (
                  <Option key={item.id}  label={item.label} value={item.label}>
                    {item.label}
                  </Option>
                ))}
                </AutoComplete>
                </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="班级" name="class">
                <AutoComplete
                  onSelect={onClassSelect}
                  onSearch={onClassSearch}
                  placeholder="请选择"
                  onChange={(value) => {
                    if (!value) {
                      setClassId()
                    }
                  }}
                >
                  {classOptions.map((item) => (
                    <Option key={item.id}  label={item.label} value={item.label}>
                      {item.label}
                    </Option>
                  ))}
                  </AutoComplete>
                </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="辅导老师" name="teacherName">
                <AutoComplete
                  onSelect={onTeacherSelect}
                  onSearch={onTeacherSearch}
                  placeholder="请选择"
                  onChange={(value) => {
                    if (!value) {
                      setTeacherId()
                    }
                  }}
                >
                  {teacherOptions.map((item) => (
                    <Option key={item.id}  label={item.label} value={item.label}>
                      {item.label}
                    </Option>
                  ))}
                  </AutoComplete>
                </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="关卡名称" name="taskName">
                <AutoComplete
                  onSelect={onTaskSelect}
                  onSearch={onTaskSearch}
                  placeholder="请选择"
                  onChange={(value) => {
                    if (!value) {
                      setTaskId()
                    }
                  }}
                >
                  {taskOptions.map((item) => (
                    <Option key={item.id}  label={item.label} value={item.label}>
                      {item.label}
                    </Option>
                  ))}
                  </AutoComplete>
                </Form.Item>
            </Col>
            <Col span={8} offset={8} style={{textAlign: 'right'}}>
              <Form.Item>
                <Button type="primary" htmlType="submit" style={{marginRight:'10px'} }>
                  查询
                </Button>
                <Button htmlType="button" onClick={onReset}>
                  重置
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>
      { !firstRender  && <ProTable<{}>
        headerTitle="数据列表"
        actionRef={actionRef}
        rowKey="key"
        search={ false}
        request={async params => {

          const msg = await queryRule({
            ...params,
            activityId,
            uid,
            groupId:classId,
            teaId:teacherId,
            mapId:taskId,
            pageNo: params.current
          })
          if(msg.code === 500){
            message.error(msg.message)
            return
          }
          if (msg.result.activityPassUserDataRespPage.records.length === 0) {
            setColumns([])
            return
          }
          return {
            data: modifyMsgData(msg.result),
            success: true,
            total: msg.result.activityPassUserDataRespPage.total
          }

        }}
        columns={columns}
        tableExtraRender={(props, dataSource) =>
          baseInfo&&
          <Card>
            <div style={{display:'flex'}}>
              <div
                style={{marginRight:'20px'}}
              >课程名称 :
              <span style={{fontSize:'17px',paddingLeft:'10px'}}>
                {baseInfo.name} {`(id:${activityId})`}
                </span>
              </div>
            </div>
          </Card>
        }
        toolbar={{
          actions: [
            <Button
                type="primary"
                disabled={lock}
                htmlType="submit"
                style={{marginRight:'10px'}}
                onClick={exportExcel}
                >
              导出
            </Button>,
          ],
        }}
        scroll={{ x: 1500 }}
      />}
    </PageContainer>
  );
};

export default TableList;
